package com.ygqh.baby.service.wechat.api;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.NameFilter;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.mp.api.TmplApi;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.foxinmy.weixin4j.mp.model.TemplateMessageInfo;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.foxinmy.weixin4j.util.NameValue;
import com.ygqh.baby.service.impl.BaseWxMpMessageService;
import com.ygqh.baby.service.wechat.message.YgSubscribeTempMsg;
import com.ygqh.baby.service.wechat.message.YgTemplateMessage;
import com.ygqh.baby.service.wechat.model.SmallTemplateMsg;

public class YgTmplApi extends TmplApi {
	private final Logger logger = Logger.getLogger(BaseWxMpMessageService.class);
	private final TokenHolder ygTokenHolder;

	public YgTmplApi(TokenHolder tokenHolder) {
		super(tokenHolder);
		this.ygTokenHolder = tokenHolder;
	}

	/**
	 * 发送小程序模板消息
	 * 
	 * @param tplMessage
	 *            消息对象
	 * @return 发送结果
	 * @throws WeixinException
	 * @see <a
	 *      href="https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#接口说明">模板消息</a>
	 */
	public JsonResult sendTmplMessage(YgTemplateMessage tplMessage) throws WeixinException {
		Token token = ygTokenHolder.getToken();
		String template_send_uri = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s";
		WeixinResponse response = weixinExecutor.post(String.format(template_send_uri, token.getAccessToken()), JSON.toJSONString(tplMessage, new NameFilter() {
			@Override
			public String process(Object object, String name, Object value) {
				if (object instanceof NameValue && name.equals("name")) {
					return "color";
				}
				return name;
			}
		}));

		return response.getAsJsonResult();
	}

	public <T extends TemplateMessage> JsonResult sendTmpleteMessage(T t) throws WeixinException {
		Token token = ygTokenHolder.getToken();
		String template_send_uri = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s";
		WeixinResponse response = weixinExecutor.post(String.format(template_send_uri, token.getAccessToken()), JSON.toJSONString(t, new NameFilter() {
			@Override
			public String process(Object object, String name, Object value) {
				if (object instanceof NameValue && name.equals("name")) {
					return "color";
				}
				return name;
			}
		}));

		return response.getAsJsonResult();
	}

	/** 获取帐号下已存在的模板列表
	* @Title: getSmallAllTmplMeg 
	* @Description: offset和count用于分页，表示从offset开始，拉取count条记录，offset从0开始，count最大为20。最后一页的list长度可能小于请求的count
	*  @param offset 
	*  @param count
	*  @return
	*  @throws WeixinException    入参
	* @return JsonResult    返回类型
	* @author （guohao） 
	* @throws
	* @date 2018年4月23日 上午10:21:12 
	* @version V1.0
	 */
	public List<SmallTemplateMsg> getSmallTmplMsgList(int offset, int count) throws WeixinException {
		Token token = ygTokenHolder.getToken();
		String url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=%s";

		JSONObject ob = new JSONObject();
		ob.put("offset", offset);
		ob.put("count", count);
		WeixinResponse response = weixinExecutor.post(String.format(url, token.getAccessToken()), ob.toJSONString());

		return JSON.parseArray(response.getAsJson().getString("list"), SmallTemplateMsg.class);
	}

	public List<TemplateMessageInfo> getSmallTmplateMsgList(int offset, int count) throws WeixinException {
		Token token = ygTokenHolder.getToken();
		String url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=%s";

		JSONObject ob = new JSONObject();
		ob.put("offset", offset);
		ob.put("count", count);
		WeixinResponse response = weixinExecutor.post(String.format(url, token.getAccessToken()), ob.toJSONString());

		return JSON.parseArray(response.getAsJson().getString("list"), TemplateMessageInfo.class);
	}

	public List<SmallTemplateMsg> getSmallAllTmplMsg() {
		Boolean flag = true;
		int offset = 0;
		int count = 20;
		List<SmallTemplateMsg> resultList = new ArrayList<>();
		while (flag) {
			List<SmallTemplateMsg> list;
			try {
				list = this.getSmallTmplMsgList(offset, count);
				if (CollectionUtils.isNotEmpty(list)) {
					resultList.addAll(list);
					if (list.size() < 20) {
						flag = false;
					}
					offset += 20;
				}
			} catch (WeixinException e) {
				e.printStackTrace();
				logger.error("获取小程序模板消息列表失败；" + e.getMessage());
				break;
			}
		}

		return resultList;
	}

	public List<TemplateMessageInfo> getSmallAllTmplateMsg() {
		Boolean flag = true;
		int offset = 0;
		int count = 20;
		List<TemplateMessageInfo> resultList = new ArrayList<>();
		while (flag) {
			List<TemplateMessageInfo> list;
			try {
				list = this.getSmallTmplateMsgList(offset, count);
				if (CollectionUtils.isNotEmpty(list)) {
					resultList.addAll(list);
					if (list.size() < 20) {
						flag = false;
					}
					offset += 20;
				}
			} catch (WeixinException e) {
				e.printStackTrace();
				logger.error("获取小程序模板消息列表失败；" + e.getMessage());
				break;
			}
		}

		return resultList;
	}

	/**
	 * 发送一次性订阅消息
	 * 
	 * @Title: sendTmplMessage
	 * @param tplMessage
	 * @throws WeixinException
	 *             入参
	 * @return JsonResult 返回类型
	 * @author （guohao）
	 * @throws
	 * @date 2017年9月8日 上午10:32:53
	 * @version V1.0
	 */
	public JsonResult sendTmplMessage(YgSubscribeTempMsg tplMessage) throws WeixinException {
		Token token = ygTokenHolder.getToken();
		String template_send_uri = "https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=%s";
		WeixinResponse response = weixinExecutor.post(String.format(template_send_uri, token.getAccessToken()), JSON.toJSONString(tplMessage, new NameFilter() {
			@Override
			public String process(Object object, String name, Object value) {
				if (object instanceof NameValue && name.equals("name")) {
					return "color";
				}
				return name;
			}
		}));

		return response.getAsJsonResult();
	}
}
